<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="排序六：堆排序, 湮灭星空,博客,Python,后端">
    <meta name="description" content="排序六：堆排序
前言
堆排序是一种选择排序。
选择排序，每次遍历从待排序序列中选出最小数，顺序地放在已排序的序列末尾，直到全部排序结束为止。
算法思想
堆排序是利用堆得性质进行的一种选择排序。
动态效果示意图：

堆是一颗顺序储存的完全二叉">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>排序六：堆排序 | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/23.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        排序六：堆排序
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E7%AE%97%E6%B3%95/">
                                <span class="chip bg-color">算法</span>
                            </a>
                        
                            <a href="/tags/%E6%8E%92%E5%BA%8F/">
                                <span class="chip bg-color">排序</span>
                            </a>
                        
                            <a href="/tags/%E4%B8%8D%E7%A8%B3%E5%AE%9A%E7%AE%97%E6%B3%95/">
                                <span class="chip bg-color">不稳定算法</span>
                            </a>
                        
                            <a href="/tags/%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F/">
                                <span class="chip bg-color">选择排序</span>
                            </a>
                        
                            <a href="/tags/%E5%A0%86%E6%8E%92%E5%BA%8F/">
                                <span class="chip bg-color">堆排序</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Tech/" class="post-category">
                                Tech
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-12-02
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2019-12-03
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2.9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    11 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="排序六：堆排序"><a class="header-anchor" href="#排序六：堆排序"></a>排序六：堆排序</h1>
<h2 id="前言"><a class="header-anchor" href="#前言"></a>前言</h2>
<p>堆排序是一种<strong>选择排序</strong>。</p>
<p><strong>选择排序</strong>，每次遍历从待排序序列中选出最小数，顺序地放在已排序的序列末尾，直到全部排序结束为止。</p>
<h2 id="算法思想"><a class="header-anchor" href="#算法思想"></a>算法思想</h2>
<p>堆排序是利用堆得性质进行的一种选择排序。</p>
<p><strong>动态效果示意图</strong>：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-041541.gif" alt="排序（6）：堆排序"></p>
<p><strong>堆</strong>是一颗<strong>顺序储存</strong>的<strong>完全二叉树</strong>。</p>
<ul>
<li>其中每个结点的关键字都<strong>不大于</strong>其子节点的关键字，称为<strong>小根堆</strong>。</li>
<li>其中每个结点的关键字都<strong>不小于</strong>其子节点的关键字，称为<strong>大根堆</strong>。</li>
</ul>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-074928.png" alt="大根堆"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-075001.png" alt="小根堆"></p>
<p><strong>完全二叉树</strong> 是 一种除了最后一层之外的其他每一层都被完全填充，并且所有结点都保持向左对齐的树，向左对齐指的是：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-074859.png" alt="向左对齐的完全二叉树"></p>
<p>像这样的树就不是完全二叉树：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-075213.png" alt="这不是完全二叉树"></p>
<p>如果给上面的大小根堆的根节点从1开始编号，则满足下面关系(下图就满足这个关系)：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-075305.png" alt="满足关系"></p>
<p>如果把这些数字放入数组中，则如下图所示，其中上面的数字是数组下标值，第一个元素占位用。</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-084533.png" alt="数组中的大根堆"></p>
<h3 id="堆排序算法详解"><a class="header-anchor" href="#堆排序算法详解"></a>堆排序算法详解</h3>
<p>以大根堆为例的堆排序思想：</p>
<ol>
<li>将待排序数组<strong>构造成大根堆</strong>；</li>
<li><strong>取出</strong>这个大根堆的堆顶点（最大值），与堆得最下最右的元素进行<strong>交换</strong>，然后把剩下的元素再构造出一个大根堆；</li>
<li><strong>重复</strong>第二步，直到这个大根堆的<strong>长度为 1</strong>，此时完成排序。</li>
</ol>
<p><strong>下面通过图片来看下，第二个步骤是如何进行的：</strong></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-085002.png" alt="首先将 2 和 90 的位置进行互换"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-085037.png" alt="互换位置后，将 2 的位置进行调整，重新构造成一个大根堆"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-085116.png" alt="构造结果"></p>
<p>如上图所示，这就选出了一个元素，然后再把 10 和 80 的位置互换，继续进行上面的步骤。</p>
<p>这就是构建大根堆的思想，编码时主要解决两个问题：</p>
<ul>
<li>如何将一个序列构造成一个大根堆？</li>
<li>输出堆顶元素后，如何将剩下的元素构造成一个大根堆？</li>
</ul>
<p>因为数组的下标是从 0 开始的，数的节点是用 1 开始的，所以需要引入一个辅助变量。Python 的列表是一个线性表，由于需要在<strong>左边追加</strong>辅助位，使用线性表做，需要将数组整体右移，开销很大。但是在链表里做这种操作就很简单了，Python 的 <code>collections</code> 库里，提供了链表结构 <code>deque</code>，我们先使用它初始化与一个无序序列：</p>
<pre><code class="language-python">In [2]: from collections import deque
In [3]: L = deque([50, 16, 30, 10, 60,  90,  2, 80, 70])
In [4]: L.appendleft(0)
In [5]: L
Out[5]: deque([0, 50, 16, 30, 10, 60, 90, 2, 80, 70])
</code></pre>
<p>根据上面的找出的两个难点，可以先编写出 <code>heap_sort</code> 函数：</p>
<pre><code class="language-python">def heap_sort(k: List) -&gt; List:
    &quot;&quot;&quot;
    堆排序
    1.将序列构造成大根堆（完全二叉树）
    2.遍历二叉树，每次从最大堆内取出最大的数，再调整大根堆
    :param k: 原序列
    :return: 有序序列
    &quot;&quot;&quot;
    if len(k) &lt; 2:
        return k

    l = deque(k)  # 将原序列转为 deque 对象，可以左边添加元素
    l.appendleft(0)  # 左边补一位 0，因为列表索引的下标是 0 开始，树的索引是 1 开始

    length = len(l) - 1  # 原序列的长度
    count = length // 2  # 所有父节点的个数
    for i in range(count, 0, -1):  # 初始化成大根堆，倒序遍历所有父节点，按照从右向左、从下到上进行逐个调整每个子树，i 就表示父节点
        heap_adjust(l, i, length)  # 起始位：父节点的索引是 i（请看图），结束位：树长 length

    for i in range(length, 0, -1):  # 倒序遍历树，i 就表示末尾子节点，每循环一次，取出一个最大数，再重新调整
        l[1], l[i] = l[i], l[1]  # 将首尾元素调换
        heap_adjust(l, 1, i - 1)  # 起始位：1，结束位：i-1 （减去刚刚抛出的一个节点）
    return list(l)[1:]  # 将 deque 转换为 list，除去第一位（因为手动添加了）返回
</code></pre>
<p><strong>详解</strong>：</p>
<ul>
<li>因为引入了辅助空间，所以 <code>length=len(l) - 1</code></li>
<li>第一个循环：将序列调整为一个大根堆（<code>heap_adjust</code>函数）</li>
<li>第二个循环：
<ul>
<li>将堆顶元素与堆尾元素互换</li>
<li>再将堆重新调整为大根堆（<code>heap_adjust</code>函数）</li>
</ul>
</li>
</ul>
<p>我们要排序的序列为 <code>deque([50, 16, 30, 10, 60, 90, 2, 80, 70])</code>，但是在第一个循环中使用的是一个辅助变量 <code>count</code>，循环时，这个值变化的顺序是 <code>4-&gt;3-&gt;2-&gt;1</code>。这是因为 4、3、2、1 代表的是<strong>有子节点的节点</strong>，从下图可以看出，而我们所谓的调整大根堆，其实就是按照从右向左、从下到上的顺序，把每颗小树调整为一个大根堆。<code>4-&gt;3-&gt;2-&gt;1</code> 的调整，其实就是 <code>10-&gt;30-&gt;16-&gt;50</code>的调整。</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-101714.png" alt="第一次循环节点的含义"></p>
<p>下面看看最关键的堆调整函数 <code>heap_adjust</code>：</p>
<pre><code class="language-python">def heap_adjust(l: deque, start: int, end: int) -&gt; None:
    &quot;&quot;&quot;
    原地调整堆结构，使之成为大根堆，不需要返回
    :param l: 堆
    :param start: 调整的起始位置
    :param end: 调整的结束位置
    :return:
    &quot;&quot;&quot;
    i = start  # i 表示一个父节点
    j = 2 * i  # 父节点的左子节点
    while j &lt;= end:
        if j &lt; end and l[j] &lt; l[j + 1]:  # 如果左子节点小于右子节点，就执行 j=j+1 这样 j 就表示的就是最大的子节点了
            j += 1
        if l[j] &gt; l[i]:  # 如果较大的子节点大于父节点，就将两者调换，再向下继续调整
            l[i], l[j] = l[j], l[i]

            i = j  # 把当前的子节点作为父节点
            j = 2 * i  # j 表示左子节点，在不超出树范围的情况下，重复以上操作
        else:  # 如果最大子节点都小于父节点，说明这个父节点对应的子树顺序正确，调整完毕退出循环
            break
</code></pre>
<p>这段代码比较抽象，我们结合实际例子来看下：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-101945.png" alt="处理过程"></p>
<ul>
<li>
<p>第一个循环第一次调用 <code>heap_adjust</code> 函数的时候，</p>
<pre><code class="language-python">i = start = 4
end = 9
l = [0, 50, 16, 30, 10, 60, 90, 2, 80, 70]
j = 2 * i
</code></pre>
<p>其中 <code>i</code>表示一个父节点（第四个节点），<code>j</code>表示父节点的左子节点（第四个节点的左子节点）（其中下标是两倍关系是数结构决定的，无可争议），</p>
</li>
<li>
<p>接着开始循环，循环条件 <code>j &lt;= end</code>表示在调整完整棵树之前一直进行循环。第一个条件 <code>if j &lt; end and l[j] &lt; l[j + 1]</code>是要保证 <code>j</code> 取到较大子树的坐标，由于左子树大于右子树，所以这个 <code>j+=1</code>不执行。<br>
<img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-103057.png" alt="第四个节点子树"></p>
</li>
<li>
<p>第二个 <code>if l[j] &gt; l[i]</code>表达式，要做的事情是，如果根节点小于最大子节点</p>
<ul>
<li>就将两者交换；</li>
<li>将刚才的 <code>j</code> 节点作为父节点，再找到该节点的子节点，重新循环，直至树末尾</li>
</ul>
<p>这样就表示将这个课子树以及下面的所有子树全部调整完毕。</p>
</li>
</ul>
<p>经过 4 次调整之后，这颗树就变成了一个大根堆，此时序列变成了这样：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-103613.png" alt="第一个循环之后的序列"></p>
<ul>
<li>
<p>第二个循环</p>
<pre><code class="language-python">for i in range(length, 0, -1):  # 倒序遍历树，i 就表示末尾子节点，每循环一次，取出一个最大数，再重新调整
	l[1], l[i] = l[i], l[1]  # 将首尾元素调换
  heap_adjust(l, 1, i - 1)  # 起始位：1，结束位：i-1 （减去刚刚抛出的一个节点）
</code></pre>
<ul>
<li>首先交换树首与树尾，此时序列变成了 <code>[16, 80, 50, 70, 60, 30, 2, 10, 90]</code></li>
<li>重新调整成大根堆，因为之前调整过一次了，现在只是首尾数据变动，所以，只需要从堆顶进行小范围调整就可以了，调整后的堆变为：</li>
</ul>
</li>
</ul>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-104233.png" alt="调整过程"></p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-104251.jpg" alt="调整的结果"></p>
<p>然后继续把 10 和 80 进行交换，继续调整，直到遍历完整个序列为止。</p>
<h3 id="python-代码实现"><a class="header-anchor" href="#python-代码实现"></a>Python 代码实现</h3>
<pre><code class="language-python">def heap_sort(k: List) -&gt; List:
    &quot;&quot;&quot;
    堆排序
    1.将序列构造成大根堆（完全二叉树）
    2.遍历二叉树，每次从最大堆内取出最大的数，再调整大根堆
    :param k: 原序列
    :return: 有序序列
    &quot;&quot;&quot;
    if len(k) &lt; 2:
        return k

    l = deque(k)  # 将原序列转为 deque 对象，可以左边添加元素
    l.appendleft(0)  # 左边补一位 0，因为列表索引的下标是 0 开始，树的索引是 1 开始

    length = len(l) - 1  # 原序列的长度
    count = length // 2  # 所有父节点的个数
    for i in range(count, 0, -1):  # 初始化成大根堆，倒序遍历所有父节点，按照从右向左、从下到上进行逐个调整每个子树，i 就表示父节点
        heap_adjust(l, i, length)  # 起始位：父节点的索引是 i（请看图），结束位：树长 length

    for i in range(length, 0, -1):  # 倒序遍历树，i 就表示末尾子节点，每循环一次，取出一个最大数，再重新调整
        l[1], l[i] = l[i], l[1]  # 将首尾元素调换
        heap_adjust(l, 1, i - 1)  # 起始位：1，结束位：i-1 （减去刚刚抛出的一个节点）
    return list(l)[1:]  # 将 deque 转换为 list，除去第一位（因为手动添加了）返回


def heap_adjust(l: deque, start: int, end: int) -&gt; None:
    &quot;&quot;&quot;
    原地调整堆结构，使之成为大根堆，不需要返回
    :param l: 堆
    :param start: 调整的起始位置
    :param end: 调整的结束位置
    :return:
    &quot;&quot;&quot;
    i = start  # i 表示一个父节点
    j = 2 * i  # 父节点的左子节点
    while j &lt;= end:
        if j &lt; end and l[j] &lt; l[j + 1]:  # 如果左子节点小于右子节点，就执行 j=j+1 这样 j 就表示的就是最大的子节点了
            j += 1
        if l[j] &gt; l[i]:  # 如果较大的子节点大于父节点，就将两者调换，再向下继续调整
            l[i], l[j] = l[j], l[i]

            i = j  # 把当前的子节点作为父节点
            j = 2 * i  # j 表示左子节点，在不超出树范围的情况下，重复以上操作
        else:  # 如果最大子节点都小于父节点，说明这个父节点对应的子树顺序正确，调整完毕退出循环
            break
</code></pre>
<h2 id="算法分析"><a class="header-anchor" href="#算法分析"></a>算法分析</h2>
<h3 id="性能"><a class="header-anchor" href="#性能"></a>性能</h3>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-104642.png" alt="排序（6）：堆排序"></p>
<h3 id="时间复杂度"><a class="header-anchor" href="#时间复杂度"></a>时间复杂度</h3>
<p>首先计算建立堆得时间：</p>
<pre><code class="language-python">count = length // 2  
for i in range(count, 0, -1):  
  heap_adjust(l, i, length)
</code></pre>
<p>n 个节点，从第 <code>0</code> 层至第 $logn$ 层（ <code>n</code> 个元素的数，层数可以表示为 $logn$ ）。对于第 <code>i</code> 层的 <code>2i</code> 个点，如果需要往下走 $logn-i$ （因为要走到底=总层数 - i 层），那么把走的所有步相加得：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/ipic/2019-12-02-110806.png" alt="排序（6）：堆排序"></p>
<p>接下来就是排序的时间：</p>
<pre><code class="language-python">for i in range(length, 0, -1):
  l[1], l[i] = l[i], l[1]
  heap_adjust(l, 1, i - 1) 
</code></pre>
<p><code>heap_adjust</code> 耗时 $logn$，共 <code>n</code> 次，故排序时间为 $O(nlogn)$。</p>
<p>堆得存储表示是<strong>顺序的</strong>。因为堆所对应的二叉树为完全二叉树，而完全二叉树通常采用顺序存储方式。</p>
<p>如果想得到一个序列中第 <code>k</code>个最小的元素之前的部分排序序列，最好采用堆排序。</p>
<h3 id="稳定性"><a class="header-anchor" href="#稳定性"></a>稳定性</h3>
<p>堆排序是一种<strong>不稳定</strong>算法。</p>
<p>因为在堆得调整过程中，关键字进行比较或者交换所走的是该节点到叶子节点的一条路径，因此对于相同的关键字就可能出现排在后面的关键字被交换到前面的情况。</p>
<h2 id="引用地址"><a class="header-anchor" href="#引用地址"></a>引用地址</h2>
<p><a href="https://www.jianshu.com/p/d174f1862601" target="_blank" rel="noopener">堆排序的Python实现(附详细过程图和讲解)</a></p>
<p><a href="https://cuijiahua.com/blog/2018/01/algorithm_6.html" target="_blank" rel="noopener">排序（6）：堆排序</a></p>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2019/12/02/suan-fa/pai-xu-liu-dui-pai-xu/">https://www.klause.cn/2019/12/02/suan-fa/pai-xu-liu-dui-pai-xu/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E7%AE%97%E6%B3%95/">
                                    <span class="chip bg-color">算法</span>
                                </a>
                            
                                <a href="/tags/%E6%8E%92%E5%BA%8F/">
                                    <span class="chip bg-color">排序</span>
                                </a>
                            
                                <a href="/tags/%E4%B8%8D%E7%A8%B3%E5%AE%9A%E7%AE%97%E6%B3%95/">
                                    <span class="chip bg-color">不稳定算法</span>
                                </a>
                            
                                <a href="/tags/%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F/">
                                    <span class="chip bg-color">选择排序</span>
                                </a>
                            
                                <a href="/tags/%E5%A0%86%E6%8E%92%E5%BA%8F/">
                                    <span class="chip bg-color">堆排序</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/12/02/suan-fa/pai-xu-qi-gui-bing-pai-xu/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/11.jpg" class="responsive-img" alt="排序七：归并排序">
                        
                        <span class="card-title">排序七：归并排序</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            排序七：归并排序
前言
归并排序是建立在归并操作上的一种有效的排序算法，采用分治法（Divide and Conquer）的一个非常典型的应用。
算法思想
归并排序采用经典的分治法策略将问题分解成一些小问题然后递归求解，而治的阶段则将分的阶
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-12-02
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/%E6%8E%92%E5%BA%8F/">
                        <span class="chip bg-color">排序</span>
                    </a>
                    
                    <a href="/tags/%E7%A8%B3%E5%AE%9A%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">稳定算法</span>
                    </a>
                    
                    <a href="/tags/%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F/">
                        <span class="chip bg-color">归并排序</span>
                    </a>
                    
                    <a href="/tags/%E5%88%86%E6%B2%BB%E6%B3%95/">
                        <span class="chip bg-color">分治法</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/12/02/suan-fa/pai-xu-wu-jian-dan-xuan-ze-pai-xu/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/19.jpg" class="responsive-img" alt="排序五：简单选择排序">
                        
                        <span class="card-title">排序五：简单选择排序</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            排序五：简单选择排序
前言
简单选择排序是一种选择排序。
选择排序：每次遍历从序列中找出最小的数，顺序地放在已排序序列的末尾，直到全部排序结束。
算法思想
选择排序很简单，大致处理流程为：

从待排序序列中，找到关键元素（最小元素）；
如果
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-12-02
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/%E6%8E%92%E5%BA%8F/">
                        <span class="chip bg-color">排序</span>
                    </a>
                    
                    <a href="/tags/%E4%B8%8D%E7%A8%B3%E5%AE%9A%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">不稳定算法</span>
                    </a>
                    
                    <a href="/tags/%E7%AE%80%E5%8D%95%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F/">
                        <span class="chip bg-color">简单选择排序</span>
                    </a>
                    
                    <a href="/tags/%E9%80%89%E6%8B%A9%E6%8E%92%E5%BA%8F/">
                        <span class="chip bg-color">选择排序</span>
                    </a>
                    
                    <a href="/tags/%E5%8E%9F%E5%9C%B0%E6%8E%92%E5%BA%8F/">
                        <span class="chip bg-color">原地排序</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>


    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
